<?php
/**
 * Created by PhpStorm.
 * User: changshuiwang
 * Date: 2016/8/2
 * Time: 17:51
 */

namespace common\service;
use yii;
use SohuCS\Scs\ScsClient;
use yii\base\Exception;
use yii\web\UploadedFile;

class ImgUpdate
{
    const SCS_ACCESS_KEY='CJHHdlldG5Xa81SiEaVTIA==';
    const SCS_SECRET_KEY='Y9ISSAwPEkn/VGalG3r1lg==';
    const HOST='http://bjcnc.azure.sohuno.com';

    public static $type=array(
        'image/jpeg','image/png','image/jpg'
    );

    public static $ext=array(
        'jpeg','png','jpg'
    );

    /**
     * @param $file
     * @return string 返回一个json响应
     */
    public static function uploadToScs($file,$bucket='focus-img')
    {
        try{
            
            $filename=$file['file']['name'];
            $tmp_name=$file['file']['tmp_name'];
            
            //检查文件合法
            self::checkImgExt($filename,$tmp_name);

            
            if($file['file']){
                $ext=self::getExtension($filename);
                $client = ScsClient::factory(array(
                    'key'      => self::SCS_ACCESS_KEY,
                    'secret'   => self::SCS_SECRET_KEY,
                    'region'   => "bjcnc"
                ));

                //判断bucket是否存在
                if(!$client->doesBucketExist($bucket)){
                    $result = $client->createBucket(array(
                        'Bucket' => $bucket,
                        'LocationConstraint' => 'bjcnc.azure.sohuno.com'
                    ));
                    $client->waitUntilBucketExists(array('Bucket' => $bucket));
                }

                $randName=uniqid().'.'.$ext;
                $filename="dianping/photos/".date('Ym',time())."/".$randName;//上传之后的文件名
                $pathToFile=$tmp_name;//图片上传之后php生成的临时文件名

                $result = $client->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $filename,
                    'Body' => fopen($pathToFile,'r+'),
                ));

                return json_encode(array(
                    'status'=>'success',
                    'msg'=>self::HOST.'/'.$bucket.'/'.$filename,
                ));
            }else{
                throw new Exception("图片不能为空");
            }
        }catch(Exception $e){
            return json_encode(array(
                'status'=>'error',
                'msg'=>$e->getMessage(),
            ));
        }
    }

    /**
     * @param $file 上传的图片 $_FILES
     * @return string 返回json串
     */
    public static function uploadToLocal($file)
    {
        try{
            $image=UploadedFile::usrLoadFiles();//获取到图片上传类
            if($image){
                //检查文件合法
                $filename=$file['file']['name'];
                $tmp_name=$file['file']['tmp_name'];
                self::checkImgExt($filename,$tmp_name);
                //将图片移动到指定目录下
                $image=$image['file'];
                $ext = $image->getExtension();
                $randName = uniqid() . "." . $ext;
                $path = date('y-m-d',time());
                $rootPath = 'uploads/' . $path . "/";
                //文件上传路径，使用的是相对路径，如果以/开头，linux上会从系统根目录而不是web根目录
                if (!file_exists($rootPath)) {
                    mkdir($rootPath,0777);
                }
                $image->saveAs($rootPath . $randName);
                $photo = '/'.$rootPath.$randName;//图片存放到数据库的路径
                return json_encode(array(
                    'status'=>'success',
                    'msg'=>$photo,//返回给前台显示
                ));
            }else{
                throw new Exception("图片不能为空");
            }

        }catch (Exception $e){
            return json_encode(array(
                'status' => 'error',
                'msg' => $e->getMessage(),
            ));
        }
    }
    /**
     * @param $filename
     * @return mixed 返回文件后缀
     */
    private static function getExtension($filename)//上传的文件名
    {
        $info = pathinfo($filename);
        return $info['extension'];
    }

    /**
     * @param $filesrcname源文件名
     * @param $filename临时文件名
     * @throws Exception
     */
    private static function checkImgExt($filesrcname,$filename)//临时文件名
    {
        $ext=self::getExtension($filesrcname);
        //对源文件类型判断
        if(!in_array($ext, self::$ext)) {
            throw new Exception("上传只能为图片");
        }

        $size=filesize($filename);
        if($size>=1024*1024){
            throw new Exception("上传图片太大，不超过1MB");
        }

        //判断文件名是否恶意更改
        $magicFile = null;
        $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
        //3、图片类型限制，
        if ($info) {
            $result = finfo_file($info, $filename);
            finfo_close($info);
        }
        if(!in_array($result, self::$type)){
            throw new Exception("非法上传文件类型");
        }
    }
}